<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.rule_id ? $t('编辑') : $t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" width="1150px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" label-width="120px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('规则名称')" prop="rule_name">
          <el-input v-emoji v-model="record.rule_name" class="customLength" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc" class="customLength" size='small' :autosize="{ minRows: 4 }" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
        </el-form-item>
        <el-form-item :label="$t('动作')" prop="action">
          <el-select v-model="record.action" size='small'>
            <el-option v-for="(value, key) in actionList" :key="key" :label="value" :value="key" :id="`custom-dialog-${key}`">
            </el-option>
          </el-select>
        </el-form-item>
        <el-button type="success" size='small' style="margin-bottom:10px;" @click="addContent" id="custom-dialog-add-content">{{$t('添加特征')}}</el-button>
        <el-table ref="multipleTable" border :data="record.content_map" tooltip-effect="dark" size='mini'>
          <el-table-column prop="content_id" align='center' :label="$t('特征ID')" width="80" />
          <el-table-column prop="content_name" align='center' :label="$t('特征名称')" width="80">
            <template slot-scope="scope">
              <tooltip :copyText="contentNameFormat(scope.row)" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="match_type" align='center' :label="$t('匹配模式')" width="120">
            <template slot-scope="scope">
              {{$t(matchTypeList[scope.row.match_type]) }}
            </template>
          </el-table-column>
          <el-table-column prop="offset" align='center' :label="$t('偏移位置')" width="80">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.offset" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="content_len" align='center' :label="$t('匹配长度')" width="80">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.content_len" class="wid190" v-if="scope.row.regular !== 'true'">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="case" align='center' :label="$t('区分大小写')" width="100">
            <template slot-scope="scope">
              {{ scope.row.match_type === 'string'?checkbox[scope.row.case]:'' }}
            </template>
          </el-table-column>
          <el-table-column prop="regular" align='center' :label="$t('启用正则')" width="100">
            <template slot-scope="scope">
              {{ scope.row.match_type === 'string'?checkbox[scope.row.regular]:'' }}
            </template>
          </el-table-column>
          <el-table-column prop="hex" align='center' :label="$t('16进制')" width="100">
            <template slot-scope="scope">
              {{ scope.row.match_type === 'byte'?checkbox[scope.row.hex]:'' }}
            </template>
          </el-table-column>
          <el-table-column prop="match_content" align='center' :label="$t('匹配特征')" min-width="150">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.match_content" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('操作')" :width="lang==='zh' ?150:200" fixed='right'>
            <template slot-scope="scope">
              <el-button type="success" plain @click="addContent(scope.row)" size='mini' id="custom-dialog-edit">{{$t('编辑')}}</el-button>
              <el-button type="danger" plain @click="deleteRule(scope.row)" size='mini' id="custom-dialog-del">{{$t('删除')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit" id="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose" id="addClose">{{$t('取 消')}}</el-button>
    </span>

    <content-dialog v-if="addContentDialog" ref="refAddContentDialog" @addContentRows='addContentRows' @editContentRows='editContentRows'></content-dialog>
  </el-dialog>
</template>
<script>
import { addRule, editRule, delContent } from '@/api/safe/white'
import ruleArray from '../../ruleArray'
import { inputClass } from '@/utils/input-class.js'
import ContentDialog from './ContentDialog.vue'
export default {
  components: { ContentDialog },
  name: 'CustomDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateDesc = (rule, value, callback) => {
      let mat = value.match(/([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g)
      let valLength = 0
      if (mat) {
        valLength = mat.length * 3 + (String(value).length - mat.length)
      } else {
        valLength = String(value).length
      }
      if (String(value).trim() === '') {
        callback()
      } else if (valLength > 1023) {
        callback(new Error(this.$t('输入内容不应超出长度 1023 个字节')))
      } else {
        callback()
      }
    }
    return {
      lang: this.$i18n.locale,
      dialogVisible: false,
      addContentDialog: false,
      record: {
        action: 'accept',
        desc: '',
        func: 0,
        match_direction: '-',
        proto: 'custom',
        rule_id: null,
        rule_name: '',
        old_name: '',
        content_map: []
      },
      recordCopy: {
        action: 'accept',
        desc: '',
        func: 0,
        match_direction: '-',
        proto: 'custom',
        rule_id: null,
        rule_name: '',
        old_name: '',
        content_map: []
      },
      matchTypeList: ruleArray.matchTypeList,
      actionList: { 'accept': this.$t('允许'), 'alert': this.$t('告警') },
      checkbox: {
        'false': this.$t('关'),
        'true': this.$t('开')
      },
      rules: {
        rule_name: [{ required: false, validator: validateName, trigger: 'blur' }],
        desc: [{ required: false, validator: validateDesc, trigger: 'blur' }]
      }
    }
  },
   watch: {
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    init (data, name) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['msg', 'offset', 'content']
        inputClass(this.$refs, data)
      })
      if (data) {
        this.record = Object.assign(this.record, data)
        this.record.old_name = name
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.record.content_map.length < 1) {
            this.$messages.error(this.$t('请添加特征'))
          } else {
            var formData = JSON.parse(JSON.stringify(this.record))
            this.$emit('addConfigRuleMap', formData)
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.$emit('childrenClose')
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.multipleTable.clearSelection()
      this.$refs.form.resetFields()
    },
    // 添加规则按钮
    addContent (data) {
      this.addContentDialog = true
      this.$nextTick(() => {
        this.$refs.refAddContentDialog.init(data)
      })
    },
    addContentRows (data) {
      if (this.record.rule_id && this.record.old_name) {
        data['rule_id'] = this.record.rule_id
        let formData = {
          name: this.record.old_name,
          rule_id: this.record.rule_id,
          rule_map: JSON.stringify(data),
          rule_type: this.record.proto
        }
        addRule(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('添加成功'))
            this.$refs['refAddContentDialog'].close()
            this.$emit('updateCustomRuleMap')
          }
        })
      } else {
        this.record.content_map.push(data)
        this.ruleIdChange()
        this.$refs['refAddContentDialog'].close()
      }
    },
    editContentRows (data) {
      if (this.record.rule_id && this.record.old_name) {
        data['rule_id'] = this.record.rule_id
        let formData = {
          name: this.record.old_name,
          rule_id: this.record.rule_id,
          rule_map: JSON.stringify(data),
          rule_type: this.record.proto
        }
        editRule(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('编辑成功'))
            this.$refs['refAddContentDialog'].close()
            this.$emit('updateCustomRuleMap')
          }
        })
      } else {
        this.record.content_map.splice(data.content_id - 1, 1, data)
        this.ruleIdChange()
        this.$refs['refAddContentDialog'].close()
      }
    },
    deleteRule (row) {
      if (this.record.rule_id && this.record.old_name) {
        let formData = {
          name: this.record.old_name,
          rule_id: this.record.rule_id,
          content_id: row.content_id
        }
        this.$confirm(this.$t('您是否要删除所选中的特征？'), this.$t('提示'), {
          closeOnClickModal: false,
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          confirmButtonClass: 'confirmButton',
          cancelButtonClass: 'confirmCancelButton',
          type: 'warning'
        }).then(() => {
          delContent(formData).then(res => {
            if (res.status === 0) {
              this.$messages.success(this.$t('删除成功'))
              this.$emit('updateCustomRuleMap')
            }
          })
        })
      } else {
        this.record.content_map.splice(row.content_id - 1, 1)
        this.ruleIdChange()
      }
    },
    updateCustomRuleMap (data) {
      for (let item of data) {
        if (item.rule_id === this.record.rule_id) {
          this.record.content_map = item.content_map
          return
        }
      }
    },
    // 重新分配特征id
    ruleIdChange () {
      this.record.content_map.forEach((tab, index) => {
        tab.content_id = index + 1
      })
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    },
    contentNameFormat (row) {
      return row.content_name
    }
  }
}
</script>
<style lang="scss" scoped>
.customLength {
  width: 400px;
}
</style>
